<template>
  <a-card :bordered="false">
   <!--  权限类型 -->
   
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper" v-if="!customParam.batchFlag">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
           <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="权限类型">
              <a-select placeholder="请选择权限类型" v-model="queryParam.busField">
                <a-select-option @change="doSearch" :value="item.code" v-for="item in dict.orderList0" :key="item.code">{{item.name}}</a-select-option>
              </a-select> 
            </a-form-item>

          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="权限对象">
              <j-input placeholder="请输入权限对象" v-model="queryParam.busTypeName"></j-input>
            </a-form-item>

          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
             
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button v-has="'stdSample:groupDep'"  @click="gotoDetail('/stdSample/dataGroup/标准样/dep')">组织架构组管理</a-button>
      <a-button v-has="'stdSample:groupUser'" @click="gotoDetail('/stdSample/dataGroup/标准样/user')">用户组管理</a-button>
      <a-button v-if="customParam.batchFlag" @click="handleDeleteBatch(null,true)">删除全部共享范围</a-button>
      <!-- 高级查询区域 -->
      <!-- <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query> -->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item v-if="!customParam.batchFlag" key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
           <a-menu-item v-else key="1" @click="handleDeleteBatch(null)"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
     
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table v-if="!customParam.batchFlag"
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">
      <template slot="busField" slot-scope="text">
          <span >{{text|busFieldFilter}}</span >
        </template>
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
               <!-- <a-menu-item>
                <a @click="handlePermission(record)">权限管理</a>
              </a-menu-item> -->
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm  title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
               
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
      <a-table v-else
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        >
      <template slot="busField" slot-scope="text">
          <span >{{text|busFieldFilter}}</span >
        </template>
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record,rowIndex">
          <a @click="handleEditBatch(record,rowIndex)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
               <!-- <a-menu-item>
                <a @click="handlePermission(record)">权限管理</a>
              </a-menu-item> -->
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm v-if="!customParam.batchFlag" title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
                <a-popconfirm v-else title="确定删除吗?" @confirm="() => handleDeleteBatch(record)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>

    <std-sample-scope-modal ref="modalForm" :dataSource="dataSource" :customParam="customParam"  @ok="modalFormOk"></std-sample-scope-modal>
    <std-select-depart ref="permissionRef" v-show="false" @back="savePermission" customReturnField="code" customReturnTitleField="name" :backInfo="{value:'permissionValue',text:'permissionName'}" v-model="permissionValue" name="标准样权限管理" :url="'/manage/codeInfo/list'" :queryParam='{type:"标准样数据权限",pageSize:-1,isdel: 0,column:"code",order:"Asc"}' :multi="true" :replaceFields="{children:'children', title:'name', key:'code', value: 'code' }"></std-select-depart>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import StdSampleScopeModal from './modules/StdSampleScopeModal'
  import {codeInfoList,codeInfoByTypeAndParent} from '@/api/codeInfo'
  import { postAction, getAction } from '@/api/manage'
  export default {
    name: 'StdSampleScopeList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      StdSampleScopeModal,
      JInput: ()=>import('@/components/jeecg/JInput'),
      stdSelectDepart:()=> import('@/views/library/stdSample/StdSelectDepart'),
    },
    provide(){
    },
    data () {
      return {
        description: '标准样数据权限管理页面',
        // 表头
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
         
          {
            title:'权限类型',
            align:"center",
            dataIndex: 'busField',
             scopedSlots: { customRender: 'busField' }
          },
         
          {
            title:'权限对象',
            align:"center",
            dataIndex: 'busTypeName'
          },
           {
            title:'权限',
            align:"center",
            dataIndex: 'permissionName'
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'remark'
          },
         
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/stdSampleScope/list",
          delete: "/stdSampleScope/delete",
          deleteBatch: "/stdSampleScope/deleteBatch",
          exportXlsUrl: "/stdSampleScope/exportXls",
          importExcelUrl: "/stdSampleScope/importExcel",
          permissionList: "/stdSampleScope/permissionList",
          permissionSave: "/stdSampleScope/permissionSave",
          deleteBatchScope: '/stdSampleScope/deleteBatchScope',
          saveScope: '/stdSampleScope/saveScope',
        },
        dictOptions:{},
        superFieldList:[],
        dict:{
          orderList0:[]
        },
        customParam:{},
        permissionValue:'',
        currentRow:{},
        disableMixinCreated:true,
      }
    },
    created() {
    this.getSuperFieldList();
    this.initDictConfig()
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
      
    },
    filters:{
      busFieldFilter(val){
        let name = ''
        switch (val) {
          case '10':
            name = '公开'
            break;
          case '20':
            name = '组织架构组'
            break;
             case '30':
            name = '组织架构'
            break;
             case '40':
            name = '用户组'
            break;
            case '50':
            name = '用户'
            break;
          default:
            break;
        }
        return name
      }
    },
    methods: {

      initDictConfig(){
         const list = ['标准样数据权限分类']
      list.forEach((item, index)=>{
        codeInfoList({type:item,pageSize:-1,isdel: 0,column:"code",order:"Asc"}).then((res) => {
          if (res.code == 200) {
            this.dict['orderList'+ index] = res.result.records
           
          } else {
            this.$message.warning('操作异常:' + res.message)
          }
        })
      })  
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'busType',text:'权限对象'})
        fieldList.push({type:'string',value:'busTypeName',text:'权限对象名称'})

        this.superFieldList = fieldList
      },
      handlePermission(record){
        let scopeId = record.id
        this.currentRow = record
        getAction(this.url.permissionList,{scopeId}).then(res=>{
           if (res.code == 200) {
            let result = res.result||[]
            this.permissionValue = result.map(item=>{return item.permissionValue}).join(",")
            this.$refs.permissionRef.openModal()
            } else {
              this.$message.warning('操作异常:' + res.message)
            }
        })
      },
      savePermission(samplePermissions){
        if(!samplePermissions || samplePermissions.length == 0){
          this.$message.warning('请选择数据')
          return
        }
        debugger
        postAction(this.url.permissionSave,{id:this.currentRow.id,samplePermissions}).then(res=>{
           if (res.code == 200) {
              this.$message.success('操作成功')
              this.loadData()
            } else {
              this.$message.warning('操作异常:' + res.message)
            }
        })
      },
      doSearch(){
        this.selectedRowKeys = []
        this.selectionRows = []
        this.loadData(1)
      },
      gotoDetail(url) {
        let routeUrl = this.$router.resolve({
          path: url,
        })
        window.open(routeUrl.href, '_blank')
      },
      handleDeleteBatch(record = null,clearAllFlag = false){
        var that = this;
         var busField = "";
        var busType = ""
        var ids = [];
        if(record!=null){
            busField = record.busField
            busType= record.busType
            ids = [record.id]
        }else if(!clearAllFlag){
            if (this.selectedRowKeys.length <= 0) {
              this.$message.warning('请选择一条记录！');
              return;
            } 
               
            for (var a = 0; a < this.selectionRows.length; a++) {
                busField += this.selectionRows[a].busField + ",";
                busType += this.selectionRows[a].busType + ",";
                ids.push(this.selectionRows[a].id );
            }
        }
        
        let delteParam = {busField,busType,busKeys:this.customParam.busKeys,clearAllFlag}
        let content =  "是否删除数据?"
        if(clearAllFlag){
          content =  "是否删除所选目录全部共享范围数据?"
        }
        this.$confirm({
            title: "确认删除",
            content:content,
            onOk: function() {
                that.loading = true;
                postAction(that.url.deleteBatchScope, delteParam).then((res) => {
                    if (res.success) {
                      
                        
                        that.$message.success(res.message);
                        
                        that.onClearSelected();

                        if(clearAllFlag){
                          that.dataSource = []
                        }else{
                          that.dataSource =  that.dataSource.filter(item=>{
                            return ids.indexOf(item.id) == -1
                          })
                          
                        }
                        
                    } else {
                        that.$message.warning(res.message);
                    }
                }).finally(() => {
                    that.loading = false;
                });
            }
        });
            
      },
      handleEditBatch(record,rowIndex){
          record.rowIndex = rowIndex
          this.handleEdit(record)
      },
      modalFormOk(record) {
          // 新增/修改 成功时，重载列表
          if(!this.customParam.batchFlag){
            this.loadData();
            //清空列表选中
            this.onClearSelected()
          }else{
            
            record.id = record.busField + record.busType
            if(record.add){
              this.dataSource.push(record)
            }else{
                 this.dataSource.splice(record.rowIndex,1,record)
            }
          }
           
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>